<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购销单管理系统 - 登录</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", "黑体", sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .login-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 40px;
            width: 100%;
            max-width: 420px;
            text-align: center;
            backdrop-filter: blur(10px);
        }

        .logo {
            font-size: 48px;
            margin-bottom: 10px;
        }

        .title {
            font-size: 28px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
        }

        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 16px;
        }

        .sync-status {
            background: #e3f2fd;
            border: 1px solid #2196f3;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .sync-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: #2196f3;
        }

        .sync-section {
            background: linear-gradient(135deg, #e8f5e8 0%, #f0f8ff 100%);
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .sync-title {
            color: #1976d2;
            margin-bottom: 15px;
            font-size: 18px;
            font-weight: bold;
        }

        .sync-methods {
            display: grid;
            gap: 15px;
            margin-bottom: 20px;
        }

        .sync-method {
            background: white;
            border-radius: 8px;
            padding: 15px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .sync-method:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .sync-method.active {
            border-color: #667eea;
            background: #f8f9ff;
        }

        .method-title {
            font-weight: bold;
            color: #333;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .method-desc {
            font-size: 13px;
            color: #666;
            line-height: 1.4;
        }

        .sync-area {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            display: none;
        }

        .sync-area.active {
            display: block;
        }

        .qr-display {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin: 15px 0;
            min-height: 200px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .qr-canvas {
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .sync-code-display {
            background: white;
            border: 2px solid #4caf50;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            font-family: 'Courier New', monospace;
            font-size: 32px;
            font-weight: bold;
            letter-spacing: 8px;
            color: #4caf50;
            margin: 15px 0;
            min-height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .sync-code-input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-family: 'Courier New', monospace;
            font-size: 24px;
            text-align: center;
            letter-spacing: 4px;
            outline: none;
            margin-bottom: 15px;
        }

        .sync-code-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .data-area {
            width: 100%;
            height: 120px;
            padding: 10px;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            resize: vertical;
            margin-bottom: 10px;
        }

        .form-group {
            margin-bottom: 20px;
            text-align: left;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
        }

        .form-input {
            width: 100%;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
            outline: none;
        }

        .form-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 10px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #333;
            border: 2px solid #e9ecef;
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);
            color: #333;
        }

        .btn-small {
            padding: 8px 15px;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }

        .divider {
            margin: 20px 0;
            text-align: center;
            position: relative;
        }

        .divider::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e9ecef;
        }

        .divider span {
            background: rgba(255, 255, 255, 0.95);
            padding: 0 15px;
            color: #666;
        }

        .toast {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-size: 14px;
            z-index: 10000;
            opacity: 0;
            transition: all 0.3s ease;
            max-width: 300px;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        .toast.info {
            background: #17a2b8;
        }

        .toast.show {
            opacity: 1;
        }

        .help-text {
            font-size: 12px;
            color: #666;
            margin-top: 8px;
            line-height: 1.4;
        }

        .copy-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: #4caf50;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 4px 8px;
            font-size: 12px;
            cursor: pointer;
        }

        @media (max-width: 480px) {
            .login-container {
                padding: 30px 20px;
                margin: 10px;
            }

            .title {
                font-size: 24px;
            }

            .sync-code-display {
                font-size: 24px;
                letter-spacing: 4px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">🏢</div>
        <h1 class="title">购销单管理系统</h1>
        <p class="subtitle">厦门汇仕环保科技有限公司</p>

        <div class="sync-status">
            <div class="sync-indicator"></div>
            <span>本地存储 + 简化同步</span>
        </div>

        <div class="sync-section">
            <div class="sync-title">🔄 数据同步方案</div>
            
            <div class="sync-methods">
                <div class="sync-method active" onclick="selectSyncMethod('local')">
                    <div class="method-title">
                        <span>📱</span>
                        <span>本地存储</span>
                    </div>
                    <div class="method-desc">数据存储在当前设备，稳定可靠</div>
                </div>
                
                <div class="sync-method" onclick="selectSyncMethod('qr')">
                    <div class="method-title">
                        <span>📱</span>
                        <span>二维码同步</span>
                    </div>
                    <div class="method-desc">生成二维码，手机扫码快速同步</div>
                </div>
                
                <div class="sync-method" onclick="selectSyncMethod('code')">
                    <div class="method-title">
                        <span>🔢</span>
                        <span>6位数字码</span>
                    </div>
                    <div class="method-desc">生成6位数字码，简单易记</div>
                </div>
            </div>

            <!-- 二维码同步区域 -->
            <div class="sync-area" id="qrSyncArea">
                <div class="qr-display" id="qrCodeDisplay">
                    <div style="font-size: 48px; color: #ccc; margin-bottom: 10px;">📱</div>
                    <div>点击下方按钮生成二维码</div>
                </div>
                <button class="btn btn-success btn-small" onclick="generateQRCode()">📱 生成二维码</button>
                <div class="help-text">
                    生成包含6位数字码的二维码，扫码后输入数字码即可同步
                </div>
            </div>

            <!-- 数字码同步区域 -->
            <div class="sync-area" id="codeSyncArea">
                <div class="sync-code-display" id="syncCodeDisplay">
                    点击生成
                </div>
                <button class="btn btn-warning btn-small" onclick="generateSyncCode()">🔢 生成6位数字码</button>
                <button class="btn btn-success btn-small" onclick="showImportArea()">📥 输入数字码</button>
                
                <div id="importArea" style="display: none; margin-top: 15px;">
                    <input type="text" class="sync-code-input" id="syncCodeInput" 
                           placeholder="输入6位数字码" maxlength="6" pattern="[0-9]{6}">
                    <button class="btn btn-primary btn-small" onclick="importSyncCode()">确认同步</button>
                </div>
                
                <div class="help-text">
                    生成6位数字码后，在其他设备输入即可同步所有数据
                </div>
            </div>
        </div>

        <form id="loginForm">
            <div class="form-group">
                <label class="form-label" for="username">用户名</label>
                <input type="text" id="username" class="form-input" placeholder="请输入用户名" required>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="password">密码</label>
                <input type="password" id="password" class="form-input" placeholder="请输入密码" required>
            </div>
            
            <button type="submit" class="btn btn-primary">🔐 登录系统</button>
        </form>

        <div class="divider">
            <span>或</span>
        </div>

        <button class="btn btn-secondary" onclick="showRegister()">👤 注册新账户</button>

        <div id="registerSection" style="display: none; margin-top: 20px;">
            <form id="registerForm">
                <div class="form-group">
                    <label class="form-label" for="newUsername">新用户名</label>
                    <input type="text" id="newUsername" class="form-input" placeholder="请输入用户名" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="newPassword">新密码</label>
                    <input type="password" id="newPassword" class="form-input" placeholder="请输入密码" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="confirmPassword">确认密码</label>
                    <input type="password" id="confirmPassword" class="form-input" placeholder="请再次输入密码" required>
                </div>
                
                <button type="submit" class="btn btn-primary">✅ 注册账户</button>
                <button type="button" class="btn btn-secondary" onclick="hideRegister()">❌ 取消</button>
            </form>
        </div>
    </div>

    <!-- QR Code 生成库 -->
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>

    <script>
        let currentSyncMethod = 'local';
        let syncDataStore = {}; // 临时存储同步数据

        // 显示消息提示
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;
            toast.textContent = message;
            document.body.appendChild(toast);
            
            setTimeout(() => toast.classList.add('show'), 100);
            setTimeout(() => {
                toast.classList.remove('show');
                setTimeout(() => {
                    if (toast.parentNode) {
                        document.body.removeChild(toast);
                    }
                }, 300);
            }, 3000);
        }

        // 选择同步方法
        function selectSyncMethod(method) {
            currentSyncMethod = method;
            
            // 更新UI状态
            document.querySelectorAll('.sync-method').forEach(el => el.classList.remove('active'));
            event.target.closest('.sync-method').classList.add('active');
            
            // 隐藏所有同步区域
            document.querySelectorAll('.sync-area').forEach(el => el.classList.remove('active'));
            
            // 显示对应的同步区域
            if (method === 'qr') {
                document.getElementById('qrSyncArea').classList.add('active');
            } else if (method === 'code') {
                document.getElementById('codeSyncArea').classList.add('active');
            }
            
            localStorage.setItem('syncMethod', method);
        }

        // 生成6位随机数字码
        function generateRandomCode() {
            return Math.floor(100000 + Math.random() * 900000).toString();
        }

        // 生成同步码
        function generateSyncCode() {
            try {
                // 收集所有数据
                const allData = {};
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key.startsWith('user_') || key === 'orderHistory' || key === 'purchaseOrderData' || key === 'currentUser') {
                        allData[key] = localStorage.getItem(key);
                    }
                }
                
                // 生成6位数字码
                const syncCode = generateRandomCode();
                
                // 将数据存储到临时存储中（实际应用中应该存储到服务器）
                syncDataStore[syncCode] = {
                    data: allData,
                    createdAt: new Date().toISOString(),
                    expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString() // 24小时后过期
                };
                
                // 也存储到localStorage作为备份
                localStorage.setItem(`sync_${syncCode}`, JSON.stringify(syncDataStore[syncCode]));
                
                // 显示同步码
                const codeDisplay = document.getElementById('syncCodeDisplay');
                codeDisplay.innerHTML = `
                    ${syncCode}
                    <button class="copy-btn" onclick="copySyncCode('${syncCode}')">复制</button>
                `;
                
                showToast('6位数字码生成成功！', 'success');
                
            } catch (error) {
                console.error('生成数字码失败:', error);
                showToast('数字码生成失败', 'error');
            }
        }

        // 生成二维码
        function generateQRCode() {
            try {
                // 先生成6位数字码
                const syncCode = generateRandomCode();
                
                // 收集数据并存储
                const allData = {};
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    if (key.startsWith('user_') || key === 'orderHistory' || key === 'purchaseOrderData' || key === 'currentUser') {
                        allData[key] = localStorage.getItem(key);
                    }
                }
                
                syncDataStore[syncCode] = {
                    data: allData,
                    createdAt: new Date().toISOString(),
                    expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
                };
                
                localStorage.setItem(`sync_${syncCode}`, JSON.stringify(syncDataStore[syncCode]));
                
                // 创建二维码内容（只包含数字码）
                const qrContent = `购销单同步码:${syncCode}`;
                
                // 清空显示区域
                const qrDisplay = document.getElementById('qrCodeDisplay');
                qrDisplay.innerHTML = '<div style="color: #666;">正在生成二维码...</div>';
                
                // 检查QRCode库是否加载
                if (typeof QRCode !== 'undefined') {
                    // 创建canvas元素
                    const canvas = document.createElement('canvas');
                    
                    // 生成二维码
                    QRCode.toCanvas(canvas, qrContent, {
                        width: 180,
                        height: 180,
                        margin: 2,
                        color: {
                            dark: '#000000',
                            light: '#FFFFFF'
                        }
                    }, function (error) {
                        if (error) {
                            console.error('二维码生成失败:', error);
                            qrDisplay.innerHTML = `
                                <div style="color: #dc3545; padding: 20px;">
                                    <div style="font-size: 48px; margin-bottom: 10px;">❌</div>
                                    <div>二维码生成失败</div>
                                    <div style="font-size: 24px; font-weight: bold; margin: 15px 0; color: #4caf50;">
                                        数字码：${syncCode}
                                    </div>
                                    <button class="btn btn-warning btn-small" onclick="copySyncCode('${syncCode}')">
                                        复制数字码
                                    </button>
                                </div>
                            `;
                        } else {
                            qrDisplay.innerHTML = `
                                <div style="border: 2px solid #4caf50; padding: 15px; border-radius: 8px; background: white;">
                                    ${canvas.outerHTML}
                                    <div style="margin-top: 10px; font-size: 14px; color: #666;">
                                        扫描二维码获取数字码<br>
                                        或直接使用：<strong style="color: #4caf50;">${syncCode}</strong>
                                    </div>
                                    <button class="btn btn-warning btn-small" onclick="copySyncCode('${syncCode}')" style="margin-top: 10px;">
                                        📋 复制数字码
                                    </button>
                                </div>
                            `;
                            showToast('二维码生成成功！', 'success');
                        }
                    });
                } else {
                    // QRCode库未加载，显示数字码
                    qrDisplay.innerHTML = `
                        <div style="border: 2px solid #ffc107; padding: 20px; border-radius: 8px; background: #fff8e1;">
                            <div style="font-size: 48px; margin-bottom: 10px;">📱</div>
                            <div style="color: #f57c00; margin-bottom: 15px;">二维码库加载中...</div>
                            <div style="font-size: 24px; font-weight: bold; margin: 15px 0; color: #4caf50;">
                                数字码：${syncCode}
                            </div>
                            <button class="btn btn-warning btn-small" onclick="copySyncCode('${syncCode}')">
                                📋 复制数字码
                            </button>
                        </div>
                    `;
                    showToast('请使用数字码进行同步', 'info');
                }
                
            } catch (error) {
                console.error('生成二维码失败:', error);
                showToast('二维码生成失败', 'error');
            }
        }

        // 复制同步码
        function copySyncCode(code) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(code).then(() => {
                    showToast('数字码已复制到剪贴板', 'success');
                }).catch(() => {
                    fallbackCopy(code);
                });
            } else {
                fallbackCopy(code);
            }
        }

        // 备用复制方法
        function fallbackCopy(text) {
            const textArea = document.createElement('textarea');
            textArea.value = text;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
            
            try {
                document.execCommand('copy');
                showToast('数字码已复制到剪贴板', 'success');
            } catch (err) {
                showToast('复制失败，请手动复制', 'error');
            }
            
            document.body.removeChild(textArea);
        }

        // 显示导入区域
        function showImportArea() {
            document.getElementById('importArea').style.display = 'block';
            document.getElementById('syncCodeInput').focus();
            showToast('请输入6位数字码', 'info');
        }

        // 导入同步码
        function importSyncCode() {
            const syncCode = document.getElementById('syncCodeInput').value.trim();
            
            if (!syncCode) {
                showToast('请输入数字码', 'error');
                return;
            }
            
            if (!/^\d{6}$/.test(syncCode)) {
                showToast('请输入6位数字码', 'error');
                return;
            }
            
            try {
                // 先从内存中查找
                let syncData = syncDataStore[syncCode];
                
                // 如果内存中没有，从localStorage查找
                if (!syncData) {
                    const storedData = localStorage.getItem(`sync_${syncCode}`);
                    if (storedData) {
                        syncData = JSON.parse(storedData);
                    }
                }
                
                if (!syncData) {
                    showToast('数字码不存在或已过期', 'error');
                    return;
                }
                
                // 检查是否过期
                if (new Date() > new Date(syncData.expiresAt)) {
                    showToast('数字码已过期，请重新生成', 'error');
                    return;
                }
                
                const allData = syncData.data;
                
                if (confirm('导入数据将覆盖当前设备的所有数据，确定要继续吗？')) {
                    // 清除现有数据
                    const keysToRemove = [];
                    for (let i = 0; i < localStorage.length; i++) {
                        const key = localStorage.key(i);
                        if (key.startsWith('user_') || key === 'orderHistory' || key === 'purchaseOrderData') {
                            keysToRemove.push(key);
                        }
                    }
                    keysToRemove.forEach(key => localStorage.removeItem(key));
                    
                    // 导入新数据
                    let importCount = 0;
                    Object.keys(allData).forEach(key => {
                        localStorage.setItem(key, allData[key]);
                        importCount++;
                    });
                    
                    showToast(`数据同步成功！同步了 ${importCount} 项数据`, 'success');
                    
                    // 清空输入区域
                    document.getElementById('syncCodeInput').value = '';
                    document.getElementById('importArea').style.display = 'none';
                    
                    // 如果有导入的用户数据，自动填入用户名
                    const importedUsers = Object.keys(allData).filter(key => key.startsWith('user_'));
                    if (importedUsers.length > 0) {
                        const firstUser = importedUsers[0].replace('user_', '');
                        document.getElementById('username').value = firstUser;
                        showToast(`已同步用户：${firstUser}`, 'info');
                    }
                }
                
            } catch (error) {
                console.error('导入失败:', error);
                showToast('数据同步失败', 'error');
            }
        }

        // 显示/隐藏注册表单
        function showRegister() {
            document.getElementById('registerSection').style.display = 'block';
        }

        function hideRegister() {
            document.getElementById('registerSection').style.display = 'none';
        }

        // 登录处理
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                showToast('请输入用户名和密码', 'error');
                return;
            }
            
            const userKey = `user_${username}`;
            const userData = localStorage.getItem(userKey);
            
            if (!userData) {
                showToast('用户不存在，请先注册', 'error');
                return;
            }
            
            const user = JSON.parse(userData);
            if (user.password !== password) {
                showToast('密码错误', 'error');
                return;
            }
            
            // 登录成功
            const currentUser = {
                username: username,
                loginTime: new Date().toLocaleString('zh-CN'),
                syncMethod: currentSyncMethod
            };
            
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            showToast('登录成功！正在跳转...', 'success');
            
            setTimeout(() => {
                window.location.href = 'order.html';
            }, 1500);
        });

        // 注册处理
        document.getElementById('registerForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const username = document.getElementById('newUsername').value.trim();
            const password = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (!username || !password || !confirmPassword) {
                showToast('请填写所有字段', 'error');
                return;
            }
            
            if (password !== confirmPassword) {
                showToast('两次输入的密码不一致', 'error');
                return;
            }
            
            if (password.length < 6) {
                showToast('密码长度至少6位', 'error');
                return;
            }
            
            const userKey = `user_${username}`;
            if (localStorage.getItem(userKey)) {
                showToast('用户名已存在', 'error');
                return;
            }
            
            // 注册成功
            const userData = {
                username: username,
                password: password,
                registerTime: new Date().toLocaleString('zh-CN'),
                syncMethod: currentSyncMethod
            };
            
            localStorage.setItem(userKey, JSON.stringify(userData));
            showToast('注册成功！请登录', 'success');
            
            // 清空注册表单并隐藏
            document.getElementById('registerForm').reset();
            hideRegister();
            
            // 自动填入用户名
            document.getElementById('username').value = username;
        });

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 恢复同步方法设置
            const savedSyncMethod = localStorage.getItem('syncMethod') || 'local';
            if (savedSyncMethod !== 'local') {
                const methodElement = document.querySelector(`[onclick="selectSyncMethod('${savedSyncMethod}')"]`);
                if (methodElement) {
                    methodElement.click();
                }
            }
            
            // 检查是否已登录
            const currentUser = localStorage.getItem('currentUser');
            if (currentUser) {
                const user = JSON.parse(currentUser);
                showToast(`欢迎回来，${user.username}！正在跳转...`, 'info');
                setTimeout(() => {
                    window.location.href = 'order.html';
                }, 1500);
            }
            
            // 清理过期的同步数据
            for (let i = localStorage.length - 1; i >= 0; i--) {
                const key = localStorage.key(i);
                if (key && key.startsWith('sync_')) {
                    try {
                        const data = JSON.parse(localStorage.getItem(key));
                        if (new Date() > new Date(data.expiresAt)) {
                            localStorage.removeItem(key);
                        }
                    } catch (e) {
                        localStorage.removeItem(key);
                    }
                }
            }
        });

        // 限制数字码输入只能是数字
        document.addEventListener('DOMContentLoaded', function() {
            const syncCodeInput = document.getElementById('syncCodeInput');
            if (syncCodeInput) {
                syncCodeInput.addEventListener('input', function(e) {
                    // 只允许数字
                    this.value = this.value.replace(/[^0-9]/g, '');
                    // 限制长度为6位
                    if (this.value.length > 6) {
                        this.value = this.value.slice(0, 6);
                    }
                });
            }
        });
    </script>
</body>
</html>